import {
  HttpException,
  HttpStatus,
  Inject,
  Injectable,
  Scope
} from '@nestjs/common'
import { InjectModel } from '@nestjs/mongoose'
import { User, UserDocument } from './users.schema'
import { Model } from 'mongoose'
import { JwtService } from '@nestjs/jwt'
import { formatDate } from 'src/utils'
import { UserDto } from './dto/UserDto'
import { REQUEST } from '@nestjs/core'

interface RequestWithUser extends Request {
  user?: UserDto
}
@Injectable({ scope: Scope.REQUEST })
export class UsersService {
  constructor(
    @InjectModel(User.name) private readonly userModel: Model<UserDocument>,
    private jwtService: JwtService,
    @Inject(REQUEST) private readonly request: RequestWithUser
  ) {}

  /**
   * 登录方法
   */
  async login(User: UserDto): Promise<string> {
    // 1.先查询用户名是否存在
    const user = await this.userModel.findOne({ userName: User.userName })
    if (!user) {
      throw new HttpException('用户不存在', HttpStatus.BAD_REQUEST)
    }
    // 2.判断密码是否正确
    if (user.passWord !== User.passWord) {
      throw new HttpException('密码错误', HttpStatus.BAD_REQUEST)
    }
    // 3.生成tokne
    const payload = {
      userName: user.userName,
      _id: user._id?.toString()
    }
    console.log(payload, '33')

    return this.jwtService.signAsync(payload)
  }

  /**
   * 注册方法
   */
  async register(User: User) {
    // 1.先查询用户名是否存在
    const user = await this.userModel.findOne({ userName: User.userName })
    if (user) {
      throw new HttpException('用户已存在', HttpStatus.BAD_REQUEST)
    }
    User.createTime = formatDate()
    // 2.创建用户
    await this.userModel.insertOne(User)
  }

  /**
   * 查询用户信息
   */
  async getUserInfo() {
    const userInfo = await this.userModel.findById(this.request.user?._id)
    return userInfo
  }
}
